package com.cfc.stage1;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * @description: 快乐数
 * https://leetcode.cn/problems/happy-number/
 *
 * @author: yangxuan10
 * @create: 2024-05-20 14:22
 **/
public class IsHappy {

    @Test
    public void test1() {
        System.out.println("========================");
        System.out.println(isHappy(19));
    }


    /**
     * 这道题解还可以用快慢指针
     */
    public boolean isHappy1(int n) {
        int slowRunner = n;
        int fastRunner = getNext(n);
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);
            fastRunner = getNext(getNext(fastRunner));
        }
        return fastRunner == 1;
    }

    /**
     * 原创
     * @param n
     * @return
     */
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<Integer>();
        set.add(n);
        int happy = isIteratorInt(n);
        while (true) {
            if (happy == 1) {
                return true;
            }
            if (set.contains(happy)) {
                return false;
            }
            set.add(happy);
            happy = isIteratorInt(happy);
        }
    }

    /**
     * 原创
     * @param n
     * @return
     */
    public int isIteratorInt(int n) {
        double pow = 0;
        while (n >= 10) {
            int weishu = n % 10;
            //FIXME Math.pow(weishu, 2); -> weishu * weishu 效率会更快一点呢
            pow += Math.pow(weishu, 2);
            n = n / 10;
        }
        pow += Math.pow(n, 2);
        return (int) pow;
    }

    /**
     * 官方的呢
     * @param n
     * @return
     */
    public int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }
}